/**
 * recharge.js - 充值页面脚本
 */

document.addEventListener('DOMContentLoaded', function() {
  // 检查用户登录状态
  if (ApiService.redirectIfNotAuthenticated()) {
    return;
  }
  
  // 初始化组件
  const topNavBar = new TopNavBar();
  topNavBar.init();
  
  const sideBar = new SideBar();
  sideBar.init('recharge');
  
  // 加载账户余额
  loadAccountBalance();
  
  // 加载银行卡列表
  loadBankCards();
  
  // 初始化表单事件
  initFormEvents();
});

/**
 * 加载账户余额
 */
function loadAccountBalance() {
  const balanceElement = document.getElementById('account-balance');
  
  ApiService.get('/api/account/balance')
    .then(response => {
      if (response.code === 0 && response.data) {
        const balanceData = response.data;
        balanceElement.textContent = Utils.formatMoney(balanceData.availableBalance);
      }
    })
    .catch(error => {
      console.error('加载账户余额失败:', error);
      balanceElement.textContent = '加载失败';
    });
}

/**
 * 加载银行卡列表
 */
function loadBankCards() {
  const bankCardSelectElement = document.getElementById('bank-card-select');
  
  ApiService.get('/api/bankcard/list')
    .then(response => {
      if (response.code === 0 && response.data) {
        const cards = response.data;
        
        if (cards.length === 0) {
          bankCardSelectElement.innerHTML = `
            <div class="empty-state">
              <p>您还没有添加银行卡</p>
              <a href="/bankcards.html" class="btn btn-outline btn-sm mt-2">添加银行卡</a>
            </div>
          `;
          return;
        }
        
        let html = '';
        cards.forEach((card, index) => {
          const isDefault = card.isDefault === 1;
          const logoClass = getBankLogoClass(card.bankName);
          
          html += `
            <div class="bank-card-item ${index === 0 ? 'active' : ''}" data-id="${card.id}">
              <div class="bank-logo ${logoClass}">
                ${getBankShortName(card.bankName)}
              </div>
              <div class="bank-info">
                <div class="bank-name">${card.bankName} ${card.cardType === 1 ? '储蓄卡' : '信用卡'}</div>
                <div class="bank-card-number">${card.cardNumber}</div>
              </div>
              ${isDefault ? '<div class="default-badge">默认</div>' : ''}
            </div>
          `;
        });
        
        bankCardSelectElement.innerHTML = html;
        
        // 添加银行卡选择事件
        const bankCardItems = document.querySelectorAll('.bank-card-item');
        bankCardItems.forEach(item => {
          item.addEventListener('click', function() {
            bankCardItems.forEach(i => i.classList.remove('active'));
            this.classList.add('active');
          });
        });
      }
    })
    .catch(error => {
      console.error('加载银行卡列表失败:', error);
      bankCardSelectElement.innerHTML = `
        <div class="empty-state">
          <p>加载银行卡失败，请刷新页面重试</p>
        </div>
      `;
    });
}

/**
 * 初始化表单事件
 */
function initFormEvents() {
  // 快捷金额选择
  const amountOptions = document.querySelectorAll('.amount-option');
  const amountInput = document.getElementById('recharge-amount');
  
  amountOptions.forEach(option => {
    option.addEventListener('click', function() {
      const amount = this.getAttribute('data-amount');
      amountInput.value = amount;
      
      // 更新选中状态
      amountOptions.forEach(opt => opt.classList.remove('active'));
      this.classList.add('active');
    });
  });
  
  // 支付方式选择
  const paymentMethods = document.querySelectorAll('.payment-method');
  const paymentMethodInput = document.getElementById('payment-method');
  const bankCardOptionsElement = document.getElementById('bank-card-options');
  
  paymentMethods.forEach(method => {
    method.addEventListener('click', function() {
      const methodValue = this.getAttribute('data-method');
      paymentMethodInput.value = methodValue;
      
      // 更新选中状态
      paymentMethods.forEach(m => m.classList.remove('active'));
      this.classList.add('active');
      
      // 显示/隐藏银行卡选择
      if (methodValue === 'BANK_CARD') {
        bankCardOptionsElement.style.display = 'block';
      } else {
        bankCardOptionsElement.style.display = 'none';
      }
    });
  });
  
  // 提交表单事件
  const rechargeForm = document.getElementById('recharge-form');
  rechargeForm.addEventListener('submit', function(e) {
    e.preventDefault();
    
    const amount = parseFloat(amountInput.value);
    const channel = paymentMethodInput.value;
    
    // 验证金额
    if (!amount || amount <= 0) {
      document.getElementById('amount-error').textContent = '请输入有效的充值金额';
      return;
    }
    
    if (amount < 1) {
      document.getElementById('amount-error').textContent = '充值金额不能小于1元';
      return;
    }
    
    if (amount > 50000) {
      document.getElementById('amount-error').textContent = '单笔充值金额不能超过50,000元';
      return;
    }
    
    document.getElementById('amount-error').textContent = '';
    
    // 获取选中的银行卡ID（如果是银行卡支付）
    let bankCardId = null;
    if (channel === 'BANK_CARD') {
      const selectedCard = document.querySelector('.bank-card-item.active');
      if (!selectedCard) {
        Toast.error('请选择银行卡');
        return;
      }
      bankCardId = selectedCard.getAttribute('data-id');
    }
    
    // 生成唯一token（防止重复提交）
    const uniqueToken = generateUniqueToken();
    
    // 构建请求数据
    const requestData = {
      amount: amount,
      channel: channel,
      uniqueToken: uniqueToken
    };
    
    if (bankCardId) {
      requestData.bankCardId = bankCardId;
    }
    
    // 显示支付确认模态框
    showPaymentModal(amount, channel, requestData);
  });
  
  // 支付确认模态框事件
  initPaymentModal();
  
  // 支付结果模态框事件
  initResultModal();
}

/**
 * 初始化支付确认模态框
 */
function initPaymentModal() {
  const modal = document.getElementById('payment-modal');
  const closeBtn = modal.querySelector('.modal-close');
  const cancelBtn = modal.querySelector('.btn-light');
  const doneBtn = document.getElementById('payment-done-btn');
  
  // 关闭按钮
  closeBtn.addEventListener('click', function() {
    closePaymentModal();
  });
  
  // 取消按钮
  cancelBtn.addEventListener('click', function() {
    closePaymentModal();
  });
  
  // 点击模态框外部关闭
  window.addEventListener('click', function(event) {
    if (event.target === modal) {
      closePaymentModal();
    }
  });
  
  // 支付完成按钮
  doneBtn.addEventListener('click', function() {
    // 这里应该调用API查询支付状态
    const requestData = JSON.parse(localStorage.getItem('currentRechargeData') || '{}');
    
    // 模拟支付成功
    const paymentResult = {
      success: true,
      tradeNo: 'R' + new Date().getTime(),
      amount: requestData.amount,
      channel: requestData.channel,
      time: new Date().toISOString()
    };
    
    // 关闭支付确认模态框
    closePaymentModal();
    
    // 显示结果
    showPaymentResult(paymentResult);
    
    // 重新加载账户余额
    loadAccountBalance();
  });
}

/**
 * 关闭支付模态框
 */
function closePaymentModal() {
  const modal = document.getElementById('payment-modal');
  modal.style.display = 'none';
}

/**
 * 初始化支付结果模态框
 */
function initResultModal() {
  const modal = document.getElementById('result-modal');
  const closeBtn = modal.querySelector('.modal-close');
  const closeButton = modal.querySelector('.btn-light');
  const viewRecordBtn = document.getElementById('view-record-btn');
  
  // 关闭按钮
  closeBtn.addEventListener('click', function() {
    closeResultModal();
  });
  
  // 关闭按钮
  closeButton.addEventListener('click', function() {
    closeResultModal();
  });
  
  // 点击模态框外部关闭
  window.addEventListener('click', function(event) {
    if (event.target === modal) {
      closeResultModal();
    }
  });
  
  // 查看交易记录按钮
  viewRecordBtn.addEventListener('click', function() {
    window.location.href = '/transactions.html';
  });
}

/**
 * 关闭结果模态框
 */
function closeResultModal() {
  const modal = document.getElementById('result-modal');
  modal.style.display = 'none';
}

/**
 * 显示支付确认模态框
 */
function showPaymentModal(amount, channel, requestData) {
  const modal = document.getElementById('payment-modal');
  
  // 更新支付信息
  document.getElementById('confirm-amount').textContent = amount.toFixed(2);
  document.getElementById('confirm-method').textContent = getChannelName(channel);
  
  // 保存当前充值数据（用于支付完成后使用）
  localStorage.setItem('currentRechargeData', JSON.stringify(requestData));
  
  // 显示模态框
  modal.style.display = 'flex';
}

/**
 * 显示支付结果
 */
function showPaymentResult(result) {
  const modal = document.getElementById('result-modal');
  const resultContent = document.getElementById('result-content');
  
  if (result.success) {
    // 成功结果
    resultContent.innerHTML = `
      <div class="result-icon success">
        <i class="fas fa-check-circle"></i>
      </div>
      <h3 class="result-title">充值成功</h3>
      <p class="result-message">您的账户已成功充值 ¥${result.amount.toFixed(2)}</p>
      
      <div class="result-details">
        <div class="result-detail-item">
          <div class="result-detail-label">交易单号</div>
          <div class="result-detail-value" id="result-trade-no">${result.tradeNo}</div>
        </div>
        <div class="result-detail-item">
          <div class="result-detail-label">充值金额</div>
          <div class="result-detail-value" id="result-amount">¥${result.amount.toFixed(2)}</div>
        </div>
        <div class="result-detail-item">
          <div class="result-detail-label">充值方式</div>
          <div class="result-detail-value" id="result-channel">${getChannelName(result.channel)}</div>
        </div>
        <div class="result-detail-item">
          <div class="result-detail-label">充值时间</div>
          <div class="result-detail-value" id="result-time">${Utils.formatDate(new Date(result.time), true)}</div>
        </div>
      </div>
    `;
  } else {
    // 失败结果
    resultContent.innerHTML = `
      <div class="result-icon error">
        <i class="fas fa-times-circle"></i>
      </div>
      <h3 class="result-title">充值失败</h3>
      <p class="result-message">${result.message || '支付过程中出现错误，请稍后重试'}</p>
    `;
  }
  
  // 清除本地存储的充值数据
  localStorage.removeItem('currentRechargeData');
  
  // 显示模态框
  modal.style.display = 'flex';
  
  // 重置表单
  document.getElementById('recharge-form').reset();
  document.querySelectorAll('.amount-option').forEach(opt => opt.classList.remove('active'));
}

/**
 * 获取银行标志样式类
 */
function getBankLogoClass(bankName) {
  if (bankName.includes('工商')) return 'icbc';
  if (bankName.includes('农业')) return 'abc';
  if (bankName.includes('中国银行')) return 'boc';
  if (bankName.includes('建设')) return 'ccb';
  return '';
}

/**
 * 获取银行简称
 */
function getBankShortName(bankName) {
  if (bankName.includes('工商')) return 'ICBC';
  if (bankName.includes('农业')) return 'ABC';
  if (bankName.includes('中国银行')) return 'BOC';
  if (bankName.includes('建设')) return 'CCB';
  return bankName.substring(0, 2);
}

/**
 * 获取支付渠道名称
 */
function getChannelName(channel) {
  switch (channel) {
    case 'ALIPAY': return '支付宝';
    case 'WECHAT': return '微信支付';
    case 'BANK_CARD': return '银行卡';
    default: return channel;
  }
}

/**
 * 生成唯一token
 */
function generateUniqueToken() {
  return Date.now().toString(36) + Math.random().toString(36).substring(2);
}
